<template>
  <div
    class="chart-zone"
    :style="{ height: height ? height + 'px' : '100%' }"
  >
    <div
      ref="echartdiv"
      :style="{
        height: height ? height + 'px' : '100%',
        width: width ? width : '100%'
      }"
    ></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// let chart = null // chart不能在此定义，不然同一个页面有多个chart时，可能会导致数据渲染错乱
export default {
  name: 'echart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    span: {
      type: Number
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: Number
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // chart: null, // chart不能是响应式的，不然tooltip中的trigger为axis时会没有效果
    }
  },
  watch: {
    options: {
      handler(options) {
        // 设置true清空echart缓存
        if (options) {
          this.chart.setOption(options, true)
        }
      },
      deep: true
    },
    height(val) {
      this.chart.dispose()
      this.$nextTick(() => {
        this.initChart()
      })
    },
    span(val) {
      this.chart.dispose()
      this.$nextTick(() => {
        this.initChart()
      })
    }
  },
  mounted() {
    this.initChart()
    this.resizeObserver = new ResizeObserver((entries) => {
      if (this.chart) {
        this.chart.resize()
      }
    })
    this.resizeObserver.observe(this.$refs.echartdiv)
  },
  beforeUnmount() {
    this.chart = null
    if (this.resizeObserver) {
      this.resizeObserver.unobserve()
    }
  },
  methods: {
    initChart() {
      this.chart = null
      // 初始化echart
      this.chart = echarts.init(this.$refs.echartdiv)
      if (this.options) {
        this.chart.setOption(this.options, true)
      }
      // this.chart.setOption(this.options || {}, true)
    }
  }
}
</script>

<style scoped>
.chart-zone {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
